<template>
    <div class="item_center" style="width: 100%">
        <n-card
            style="min-width: 400px; width: 30vw; max-width: 500px"
            hoverable
        >
            <div
                style="
                    display: flex;
                    align-items: baseline;
                    justify-content: space-between;
                "
            >
                <h1>注册</h1>
                <n-button quaternary @click="backClick">
                    已有帐号？ 点此登录
                </n-button>
            </div>
            <n-form
                ref="registerFormRef"
                size="large"
                label-placement="top"
                :label-width="80"
                :rules="rules"
                :model="formValue"
            >
                <n-form-item label="昵称" path="nickName">
                    <n-input
                        placeholder="请输入您的昵称（可重复）"
                        v-model:value="formValue.nickName"
                        @keydown.enter.prevent
                    />
                </n-form-item>
                <n-form-item label="邮箱地址" path="email">
                    <n-input
                        placeholder="请输入您的邮箱地址（账号的唯一标识符）"
                        v-model:value="formValue.email"
                        @keydown.enter.prevent
                    />
                </n-form-item>

                <n-form-item label="密码" path="password">
                    <n-input
                        placeholder="请输入密码"
                        type="password"
                        v-model:value="formValue.password"
                        @input="handlePasswordInput"
                        @keydown.enter.prevent
                    />
                </n-form-item>

                <n-form-item
                    first
                    path="reenteredPassword"
                    label="重复密码"
                    ref="rPasswordFormItemRef"
                >
                    <n-input
                        :disabled="!formValue.password"
                        placeholder="请重复一次密码"
                        v-model:value="formValue.reenteredPassword"
                        type="password"
                        @keydown.enter.prevent
                    />
                </n-form-item>

                <n-form-item label="描述" path="description">
                    <n-input
                        type="textarea"
                        placeholder="介绍一下您自己吧！"
                        :autosize="{
                            minRows: 2,
                            maxRows: 5,
                        }"
                        v-model:value="formValue.description"
                    />
                </n-form-item>
                <n-button
                    style="width: 100%"
                    @click="registerClick"
                    type="primary"
                    size="large"
                >
                    注册
                </n-button>
            </n-form>
        </n-card>
    </div>
</template>

<script setup>
import { NButton, NInput, NForm, NFormItem, NCard, useDialog } from "naive-ui";
import { ref, defineComponent } from "vue";

import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

const dialog = useDialog();

import web_axios from "../axios";

const registerFormRef = ref(null);

const rPasswordFormItemRef = ref(null);

function validatePasswordStartWith(rule, value) {
    return (
        formValue.value.password &&
        formValue.value.password.startsWith(value) &&
        formValue.value.password.length >= value.length
    );
}
function validatePasswordSame(rule, value) {
    return value === formValue.value.password;
}

let formValue = ref({
    nickName: "",
    email: "",
    password: "",
    reenteredPassword: null,
    description: "",
});
let rules = {
    nickName: [
        {
            required: true,
            message: "请输入您的昵称",
            trigger: ["input"],
        },
    ],
    email: [
        {
            required: true,
            message: "请输入您的邮箱地址",
            trigger: ["input"],
        },
    ],
    password: [
        {
            required: true,
            message: "请输入密码",
        },
    ],
    reenteredPassword: [
        {
            required: true,
            message: "请再次输入密码",
            trigger: ["input", "blur"],
        },
        {
            validator: validatePasswordStartWith,
            message: "两次密码输入不一致",
            trigger: "input",
        },
        {
            validator: validatePasswordSame,
            message: "两次密码输入不一致",
            trigger: ["blur", "password-input"],
        },
    ],
};

function registerClick(e) {
    registerFormRef.value.validate((errors) => {
        if (!errors) {
            web_axios
                .post("/register", {
                    userName: formValue.value.email,
                    email: formValue.value.email,
                    password: formValue.value.password,
                    nickName: formValue.value.nickName,
                    description: formValue.value.description,
                })
                .then((value) => {
                    if (
                        value.data.code === 200 &&
                        value.data.msg === "操作成功"
                    ) {
                        const redirect = route.query.redirect;
                        if (redirect) {
                            router.push(redirect);
                        } else {
                            router.push("/student");
                        }
                    } else {
                        dialog.error({
                            title: "注册错误",
                            content: value.data.msg,
                            positiveText: "啊",
                        });
                    }
                })
                .catch((err) => {
                    if (err.response) {
                        dialog.error({
                            title: "注册错误",
                            content: err.response.data.msg,
                            positiveText: "啊",
                        });
                    } else {
                        web_axios.post("/logout");
                        dialog.error({
                            title: "注册错误",
                            content: "您遇到了一个未知的错误！",
                            positiveText: "感觉应该去联系工程师了",
                        });
                    }
                });
        }
    });
}

function handlePasswordInput() {
    if (formValue.value.reenteredPassword) {
        rPasswordFormItemRef.value.validate({ trigger: "password-input" });
    }
}
</script>

<script>
export default defineComponent({
    name: "Register",
    methods: {
        backClick(e) {
            this.$router.push({
                path: "login",
                query: {
                    redirect: this.$route.query.redirect, //当前页面的地址
                },
            });
        },
    },
});
</script>
